package Servlet;

import Utils.IOUtils;
import Utils.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import vo.ResultBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("欢迎用户进入");
		String jsonStr= IOUtils.readStr(req.getInputStream());
		JSONObject user=(JSONObject) JSONObject.parse(jsonStr);
		String username=user.get("username").toString();
		String password=user.get("password").toString();
		ResultBean resultBean=ResultBean.ERROR("密码或账号错误，请重新输入");
		if("admin".equals(username)&&"123456".equals(password)) {
			//每个客户端来的时候，服务器给客户端发送一个cookie，这是服务器给客户端发的
			HttpSession session=req.getSession();
			System.out.println("登录成功 "+session.getId());
			session.setAttribute("adminUser",user);
			resultBean=ResultBean.SUCCESS("admin");
		}
		//返回数据
		String respStr= JSONObject.toJSONString(resultBean);
		resp.getWriter().write(respStr);
	}
}
